package com.ruoyi.record.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.record.domain.BacklogRecord;
import com.ruoyi.record.domain.query.BacklogRecordQuery;
import com.ruoyi.record.domain.vo.BacklogRecordVo;
import com.ruoyi.record.mapper.BacklogRecordMapper;
import com.ruoyi.record.service.IBacklogRecordService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

/**
 *
 * @author lisongtao
 * @date 2023/10/24 23:41
 */
@Service
public class BacklogRecordServiceImpl implements IBacklogRecordService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BacklogRecordMapper backlogRecordMapper;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询代办/已办记录
     *
     * @param recordQuery
     */
    @Override
    public List<BacklogRecord> selectBacklogRecords(BacklogRecordQuery recordQuery) {
        return backlogRecordMapper.selectBacklogRecords(structureBacklogRecordQuery(recordQuery));
    }

    /**
     * 汇总查询代办/已办记录数目
     * @param recordQuery
     */
    @Override
    public Long countBacklogRecords(BacklogRecordQuery recordQuery) {
        return backlogRecordMapper.countBacklogRecords(structureBacklogRecordQuery(recordQuery));
    }


    private BacklogRecordQuery structureBacklogRecordQuery(BacklogRecordQuery recordQuery) {
        String flag = recordQuery.getFlag();
        if (!("0".equals(flag) || "1".equals(flag))) {
            throw new ServiceException("当前操作类型不存在！");
        }
        String originalSystemUserId = SecurityUtils.getLoginUser().getUser().getOriginalSystemUserId();
        recordQuery.setUserId(originalSystemUserId);
        return recordQuery;
    }

    /**
     * 查询代办记录详情
     *
     * @param recordQuery
     */
    @Override
    public BacklogRecord selectBacklogRecordById(BacklogRecordQuery recordQuery) {
        String id = recordQuery.getId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("流程编号不能为空！");
        }
        BacklogRecord backlogRecord = backlogRecordMapper.selectBacklogRecordById(recordQuery);
        Assert.notNull(backlogRecord, "查询办理记录为空！");
        BacklogRecord backlogRecordLocal = backlogRecordMapper.selectBackLogRecordLocal(recordQuery);
        // 获取将视频和图片集合
        if (backlogRecordLocal != null) {
            backlogRecord.setPhotoCollection(backlogRecordLocal.getPhotoCollection());
            backlogRecord.setVideoCollection(backlogRecordLocal.getVideoCollection());
        }
        return backlogRecord;
    }

    /**
     * 处理待办记录
     *
     * @param backlogRecordVo
     */
    @Override
    public void processBacklog(BacklogRecordVo backlogRecordVo) {
        String id = backlogRecordVo.getId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("流程编号不能为空！");
        }
        String agree = backlogRecordVo.getAgree();
        if (StringUtils.isBlank(agree) || !("0".equals(agree) || "1".equals(agree))) {
            throw new ServiceException("处理意见不能为空！");
        }
        String remark = backlogRecordVo.getRemark();
        if (StringUtils.isBlank(remark)) {
            throw new ServiceException("处理意见详情不能为空！");
        }
        BacklogRecordQuery recordQuery = new BacklogRecordQuery();
        recordQuery.setId(id);
        BacklogRecord backlogRecord = selectBacklogRecordById(recordQuery);
        String userId = backlogRecord.getUserId();
        if (StringUtils.isBlank(userId)) {
            throw new ServiceException("查询代办记录失败！");
        }
        String originalSystemUserId = SecurityUtils.getLoginUser().getUser().getOriginalSystemUserId();
        if (!userId.equals(originalSystemUserId)) {
            throw new ServiceException("当前用户与代办记录用户关联失败！");
        }
        String flag = backlogRecord.getFlag();
        if (!"0".equals(flag)) {
            throw new ServiceException("当前记录已完成无法处理！");
        }
        String photoCollection = backlogRecordVo.getPhotoCollection();
        String videoCollection = backlogRecordVo.getVideoCollection();

        logger.error(JSON.toJSONString(backlogRecordVo));

//      调用处理待办的接口
        String handleUrl = sysConfigService.selectConfigByKey("handle.tasks.url");
        if (StringUtils.isBlank(handleUrl)) {
            throw new ServiceException("访问内部系统待办工作处理失败！");
        }
//      handleUrl 应为  http://192.168.1.125:8080
        String url = handleUrl + "/servlet/workFlowServlet?" +
                "dbid=" + id + "&FAgree=" + agree + "&FRemark=" + remark + "&photoCollection=" + (StringUtils.isNotBlank(photoCollection) ? "(" + photoCollection + ")" : "") +
                "&videoCollection=" + (StringUtils.isNotBlank(videoCollection) ? "(" + videoCollection + ")" : "")
                + "&sqlyw=&externalInterface=wechat";
        logger.error(url);
        String response = null;
        try {
            response = HttpUtil.get(url, 5000);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        logger.error(response);
        if (StringUtils.isNotBlank(response)) {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");
            if (!"200".equals(code)) {
                throw new ServiceException("待办工作处理失败！");
            }
        } else {
            throw new ServiceException("访问内部系统待办工作处理失败！");
        }
        // 将图片和视频信息保存到本地数据库中
        backlogRecord.setAgree(agree);
        backlogRecord.setRemark(remark);
        backlogRecord.setPhotoCollection(photoCollection);
        backlogRecord.setVideoCollection(videoCollection);
        backlogRecord.setCreateBy(SecurityUtils.getUsername());
        backlogRecord.setCreateTime(new Date());
        backlogRecordMapper.insertBackLogRecord(backlogRecord);
    }


}
